package root.electronclass.electronclass.grade.rota

import android.os.Bundle
import android.view.View
import android.widget.ArrayAdapter
import androidx.appcompat.widget.ListPopupWindow
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import root.electronclass.electronclass.common.base.BasicAdapter
import root.electronclass.electronclass.common.base.ViewBindingFragment
import root.electronclass.electronclass.common.util.ToastUtil
import root.electronclass.electronclass.databinding.FragmentClassRotaAddAttendantBinding
import root.electronclass.electronclass.databinding.FragmentClassRotaAddAttendantItemBinding
import root.electronclass.electronclass.databinding.FragmentClassRotaAddAttendantStudentItemBinding
import root.electronclass.electronclass.ext.CoroutineExceptionHandler
import root.electronclass.electronclass.grade.model.ClassRota
import root.electronclass.electronclass.grade.model.Person
import root.electronclass.electronclass.grade.model.RotaUser
import root.electronclass.electronclass.mvp.rest.ClassApi


/**
 *
 * @author Lokiy
 * @date 2023/2/18 15:43
 */
class ClassAddAttendantFragment : ViewBindingFragment<FragmentClassRotaAddAttendantBinding>() {


    private val weekList = mutableListOf("周一", "周二", "周三", "周四", "周五", "周六", "周日")
    private val selectStudentList = mutableListOf<Person>()
    private val selectRoteItemList = mutableListOf<ClassRota>()
    private val selectWeekList = mutableListOf<String>()

    private val studentAdapter = BasicAdapter<Person, FragmentClassRotaAddAttendantStudentItemBinding> { holder, item ->
        holder.binding.itemName.text = item.name
        val hasSelect = selectStudentList.contains(item)
        holder.binding.root.isSelected = hasSelect
        holder.binding.root.setOnClickListener {
            if (selectStudentList.contains(item)) {
                selectStudentList.remove(item)
                holder.binding.root.isSelected = false
            } else {
                selectStudentList.add(item)
                holder.binding.root.isSelected = true
            }
        }
    }

    private val rotaItemAdapter = BasicAdapter<ClassRota, FragmentClassRotaAddAttendantItemBinding> { holder, item ->
        holder.binding.itemName.text = item.item
        holder.binding.itemRemove.setOnClickListener {
            if (selectRoteItemList.contains(item)) {
                selectRoteItemList.remove(item)
                refresh(selectRoteItemList)
            }
        }
    }

    private val weekAdapter = BasicAdapter<String, FragmentClassRotaAddAttendantItemBinding> { holder, item ->
        holder.binding.itemName.text = item
        holder.binding.itemRemove.setOnClickListener {
            if (selectWeekList.contains(item)) {
                selectWeekList.remove(item)
                refresh(selectWeekList)
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.recycler.layoutManager = FlexboxLayoutManager(view.context).apply {
            flexDirection = FlexDirection.ROW // 横向排列（默认）
            flexWrap = FlexWrap.WRAP // 自动换行（关键！）
        }
        binding.recycler.adapter = studentAdapter

        binding.rotaItemRecycler.layoutManager = LinearLayoutManager(view.context, LinearLayoutManager.HORIZONTAL, false)
        binding.rotaItemRecycler.adapter = rotaItemAdapter
        rotaItemAdapter.refresh(selectRoteItemList)

        binding.rotaWeekRecycler.layoutManager = LinearLayoutManager(view.context, LinearLayoutManager.HORIZONTAL, false)
        binding.rotaWeekRecycler.adapter = weekAdapter
        weekAdapter.refresh(selectWeekList)

        binding.save.setOnClickListener {
            if (selectStudentList.isEmpty()) {
                return@setOnClickListener ToastUtil.showToast(requireActivity(), "请选择值日生")
            }
            if (selectRoteItemList.isEmpty()) {
                return@setOnClickListener ToastUtil.showToast(requireActivity(), "请选择值日项")
            }
            if (selectWeekList.isEmpty()) {
                return@setOnClickListener ToastUtil.showToast(requireActivity(), "请选择值日日期")
            }
            showProgress("操作中", "", true)
            lifecycleScope.launch(CoroutineExceptionHandler()) {
                val response = withContext(Dispatchers.IO) {
                    ClassApi.service.addClassRotaUser(
                        RotaUser(
                            itemIds = selectRoteItemList.mapNotNull { it.id?.toInt() },
                            userIds = selectStudentList.map { it.id.toLong() },
                            weekList = selectWeekList.map { weekList.indexOf(it) + 1 },
                        )
                    )
                }
                dismissProgress()
                if (response?.code == 200) {
                    ToastUtil.showToast(requireActivity(), "创建成功")
                    requireActivity().finish()
                } else {
                    ToastUtil.showToast(requireActivity(), response?.msg ?: "创建失败")
                }
            }
        }
        getData()
    }

    private fun getData() {
        lifecycleScope.launch(CoroutineExceptionHandler()) {
            withContext(Dispatchers.IO) {
                ClassApi.service.getAllStudentList()?.rows ?: mutableListOf()
            }.let {
                studentAdapter.refresh(it)
            }
        }
        lifecycleScope.launch(CoroutineExceptionHandler()) {
            withContext(Dispatchers.IO) {
                ClassApi.service.getClassRotaList()?.rows ?: mutableListOf()
            }.let { list ->
                binding.rotaItemArrow.setOnClickListener {
                    ListPopupWindow(requireContext()).apply {
                        anchorView = it
                        isModal = true
                        val filter = list.filter { selectRoteItemList.contains(it).not() }
                        setAdapter(ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, filter.map { it.item }))
                        setOnItemClickListener { _, _, position, _ ->
                            selectRoteItemList.add(filter[position])
                            rotaItemAdapter.refresh(selectRoteItemList)
                            binding.rotaItemRecycler.scrollToPosition(selectRoteItemList.size - 1)
                            dismiss()
                        }
                    }.show()
                }
            }
        }
        binding.rotaWeekArrow.setOnClickListener {
            ListPopupWindow(requireContext()).apply {
                anchorView = it
                isModal = true
                val objects = weekList.filter { selectWeekList.contains(it).not() }
                setAdapter(ArrayAdapter(requireContext(), android.R.layout.simple_list_item_1, objects))
                setOnItemClickListener { _, _, position, _ ->
                    selectWeekList.add(objects[position])
                    weekAdapter.refresh(selectWeekList)
                    binding.rotaWeekRecycler.scrollToPosition(selectWeekList.size - 1)
                    dismiss()
                }
            }.show()
        }
    }

}